package com.tim.bos;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;

import org.hibernate.annotations.GenericGenerator;


@MappedSuperclass
@Access(AccessType.FIELD)
public class CoreObject  implements ICoreObject,Serializable {

	@Id
	@GeneratedValue(generator="bostypeidgenerator")
	@GenericGenerator(name="bostypeidgenerator",strategy="com.tim.bos.PersistantEntityIdGenerator")
	@Column(name="id",nullable=false,length=25)
	private String id;

	
	@Version
	private int version;

	@PrePersist
	@PreUpdate
	public void resetEntriesSeqAndParent() {
		List<Field> fieldlist=new ArrayList<Field>();
		Class clz=this.getClass();
		while(!clz.equals(Object.class)){
			Field[] fields=clz.getDeclaredFields();
			fieldlist.addAll(Arrays.asList(fields));
			clz=clz.getSuperclass();
		}
		for(Field f: fieldlist){
			OneToMany onetomany =f.getAnnotation(OneToMany.class);
			if(onetomany!=null){
				List list=null;
				try {
					f.setAccessible(true);  
					list = (List)f.get(this);
				} catch (IllegalArgumentException  e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}catch( IllegalAccessException e){
					e.printStackTrace();
				}
				if(list!=null){
					int seq = 0;
					for(int i=0;i<list.size();i++){
						IEntry e=(IEntry)list.get(i);
						if(e!=null){
							e.setParent(this);
							if(e.getSeq()!=seq){
								e.setSeq(seq);
							}
							seq++;
							e.resetEntriesSeqAndParent();
						}
					}
				}
			}
		}		
	}

	@Override
	public void setId(String value) {
		this.id=value;
	}

	@Override
	public String getId() {
		return this.id;
	}



}
